package com.mine.androidlearn.common.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by hujianghao5 on 2018/4/11.
 */

public class DbUtil {

    private static final String TAG = DbUtil.class.getSimpleName();
    private static Logger sLogger = LoggerFactory.getLogger(TAG);

    private SQLiteDatabase db;

    public DbUtil(Context context) {
        db = new DatabaseHelper(context).getWritableDatabase();
    }


    /**
     * 插入测试表
     *
     * @param huInfo
     * @return
     */
    public boolean insertHuInfo(DBHuInfo huInfo) {
        boolean sqlResult = false;
        if (huInfo == null) {
            return false;
        }
        ContentValues cv = new ContentValues();
        cv.put(DatabaseHelper.HU_NAME, huInfo.getHuName());
        cv.put(DatabaseHelper.HU_AGE, huInfo.getHuAge());
        cv.put(DatabaseHelper.HU_SEX, huInfo.getHuSex());
        cv.put(DatabaseHelper.HU_JOB, huInfo.getJob());

        sqlResult =db.insert(DatabaseHelper.TABLE_HU_INFO, null, cv) != -1;
        sLogger.info("insertHuInfo sqlResult:"+sqlResult);

        return sqlResult;

    }


    public List<DBHuInfo> queryHuInfo() {
        List<DBHuInfo> list = new ArrayList<DBHuInfo>();
        Cursor cursor = null;
        try {
            cursor = db.query(DatabaseHelper.TABLE_HU_INFO, null, null, null, null, null, null);
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    DBHuInfo info = new DBHuInfo();
                    info.setHuName(cursor.getString(cursor.getColumnIndex(DatabaseHelper.HU_NAME)));
                    info.setHuAge(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.HU_AGE)));
                    info.setHuSex(cursor.getString(cursor.getColumnIndex(DatabaseHelper.HU_SEX)));
                    info.setJob(cursor.getString(cursor.getColumnIndex(DatabaseHelper.HU_JOB)));
                    list.add(info);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return list;
    }

    /**
     * 删除测试
     *
     * @param name
     */
    public void deleteHuInfo(String name) {
        try {
            String sql = "delete from " + DatabaseHelper.TABLE_HU_INFO + " where "
                    + DatabaseHelper.HU_NAME + " like 'hu%'";
            sLogger.info("sql:" + sql);
            db.execSQL(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
